package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yupi.yuoj.model.dto.membership.MembershipPurchaseRequest;
import com.yupi.yuoj.model.entity.MembershipOrder;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.MembershipVO;
import com.yupi.yuoj.service.MembershipService;
import com.yupi.yuoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

/**
 * 会员服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Service
@Slf4j
public class MembershipServiceImpl implements MembershipService {

    @Resource
    private UserService userService;

    @Override
    public MembershipVO getUserMembership(User user) {
        MembershipVO membershipVO = new MembershipVO();
        
        // 检查并更新会员状态
        user = checkAndUpdateMembershipStatus(user);
        
        membershipVO.setIsVip(user.getIsVip() != null && user.getIsVip() == 1);
        membershipVO.setVipType(user.getVipType());
        membershipVO.setExpireTime(user.getVipExpireTime());
        
        // 计算剩余天数
        if (user.getVipExpireTime() != null) {
            LocalDateTime expireDateTime = user.getVipExpireTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime now = LocalDateTime.now();
            long remainingDays = ChronoUnit.DAYS.between(now, expireDateTime);
            membershipVO.setRemainingDays((int) Math.max(0, remainingDays));
        } else {
            membershipVO.setRemainingDays(0);
        }
        
        return membershipVO;
    }

    @Override
    @Transactional
    public boolean purchaseMembership(MembershipPurchaseRequest purchaseRequest, User user) {
        try {
            // 计算新的到期时间
            Date newExpireTime = calculateNewExpireTime(user, purchaseRequest.getDuration());
            
            // 更新用户会员信息
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", user.getId());
            updateWrapper.set("vip_type", purchaseRequest.getPlanId());
            updateWrapper.set("vip_expire_time", newExpireTime);
            updateWrapper.set("is_vip", 1);
            
            boolean updateResult = userService.update(updateWrapper);
            
            if (updateResult) {
                // 创建订单记录（简化版，实际项目中应该先创建订单再支付）
                MembershipOrder order = new MembershipOrder();
                order.setUserId(user.getId());
                order.setPlanId(purchaseRequest.getPlanId());
                order.setPlanName(purchaseRequest.getPlanName());
                order.setDuration(purchaseRequest.getDuration());
                order.setPrice(purchaseRequest.getPrice());
                order.setOrderStatus("paid");
                order.setPaymentMethod("mock_payment");
                order.setPaymentTime(new Date());
                order.setCreateTime(new Date());
                order.setUpdateTime(new Date());
                
                // 这里应该保存到数据库，但为了简化，我们先跳过
                log.info("会员购买成功，用户ID：{}，套餐：{}，到期时间：{}", 
                        user.getId(), purchaseRequest.getPlanName(), newExpireTime);
            }
            
            return updateResult;
        } catch (Exception e) {
            log.error("购买会员失败", e);
            return false;
        }
    }

    @Override
    public User checkAndUpdateMembershipStatus(User user) {
        if (user.getVipExpireTime() != null) {
            Date now = new Date();
            if (now.after(user.getVipExpireTime())) {
                // 会员已过期，更新状态
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", user.getId());
                updateWrapper.set("is_vip", 0);
                updateWrapper.set("vip_type", "normal");
                
                userService.update(updateWrapper);
                
                // 更新内存中的用户对象
                user.setIsVip(0);
                user.setVipType("normal");
            }
        }
        return user;
    }

    /**
     * 计算新的到期时间
     */
    private Date calculateNewExpireTime(User user, Integer duration) {
        Calendar calendar = Calendar.getInstance();
        
        // 如果用户当前是会员且未过期，从当前到期时间开始计算
        if (user.getVipExpireTime() != null && user.getVipExpireTime().after(new Date())) {
            calendar.setTime(user.getVipExpireTime());
        } else {
            // 否则从当前时间开始计算
            calendar.setTime(new Date());
        }
        
        calendar.add(Calendar.MONTH, duration);
        return calendar.getTime();
    }
}